package com.u8.sdk;

import org.json.JSONObject;

import android.app.Application;
import android.os.Bundle;
import android.util.Log;

import com.xiaomi.gamecenter.sdk.GameInfoField;
import com.xiaomi.gamecenter.sdk.MiCommplatform;
import com.xiaomi.gamecenter.sdk.MiErrorCode;
import com.xiaomi.gamecenter.sdk.OnLoginProcessListener;
import com.xiaomi.gamecenter.sdk.OnPayProcessListener;
import com.xiaomi.gamecenter.sdk.entry.MiAccountInfo;
import com.xiaomi.gamecenter.sdk.entry.MiAppInfo;
import com.xiaomi.gamecenter.sdk.entry.MiBuyInfo;

public class MiSDK {

	private static MiSDK instance;

	enum SDKState {
		StateDefault, StateIniting, StateInited, StateLogin, StateLogined
	}

	private SDKState state = SDKState.StateDefault;

	private String appID;
	private String appKey;

	private boolean loginAfterInited = false;

	public static MiSDK getInstance() {
		if (instance == null) {
			instance = new MiSDK();
		}
		return instance;
	}

	private MiSDK() {

	}

	private void parseSDKParams(SDKParams params) {

		this.appID = params.getString("AppID");
		this.appKey = params.getString("AppKey");

	}

	public void initSDK(Application context, SDKParams params) {
		this.parseSDKParams(params);
		this.initSDK(context);
	}

	private void initSDK(Application context) {
		Log.d("xiaomi", "初始化");
		this.state = SDKState.StateIniting;

		try {

			MiAppInfo appInfo = new MiAppInfo();
			appInfo.setAppId(this.appID);
			appInfo.setAppKey(this.appKey);
			MiCommplatform.Init(context, appInfo);
			// U8SDK.getInstance().onResult(U8Code.CODE_INIT_SUCCESS,
			// "init success");
			this.state = SDKState.StateInited;

		} catch (Exception e) {
			// U8SDK.getInstance().onResult(U8Code.CODE_INIT_FAIL,
			// e.getMessage());
			e.printStackTrace();
		}

	}

	public void login() {
		Log.d("xiaomi", "登录");
		if (state.ordinal() < SDKState.StateInited.ordinal()) {
			initSDK(U8SDK.getInstance().getApplication(), U8SDK.getInstance()
					.getSDKParams());
		}

		if (!SDKTools.isNetworkAvailable(U8SDK.getInstance().getContext())) {
			U8SDK.getInstance().onResult(U8Code.CODE_NO_NETWORK,
					"The network now is unavailable");
			return;
		}
		try {

			MiCommplatform.getInstance().miLogin(
					U8SDK.getInstance().getContext(),
					new OnLoginProcessListener() {

						@Override
						public void finishLoginProcess(int code,
								MiAccountInfo account) {

							switch (code) {
							case MiErrorCode.MI_XIAOMI_PAYMENT_SUCCESS:
								state = SDKState.StateLogined;

								long uid = account.getUid();
								String session = account.getSessionId();
								U8SDK.getInstance().onResult(
										U8Code.CODE_LOGIN_SUCCESS, uid + "");

								U8SDK.getInstance().onLoginResult(
										encodeLoginResult(session, uid + ""));
								break;
							default:
								state = SDKState.StateInited;
								U8SDK.getInstance().onResult(
										U8Code.CODE_LOGIN_FAIL,
										"login failed.code:" + code);
							}

						}
					});

		} catch (Exception e) {
			U8SDK.getInstance()
					.onResult(U8Code.CODE_LOGIN_FAIL, e.getMessage());
			e.printStackTrace();
		}
	}

	private LoginResult encodeLoginResult(String sid, String uid) {

		String sdkVersion = "1.0.0";
		String sp_id = "xiaomi";
		String appid = U8SDK.getInstance().getAppID();
		LoginResult loginResult = new LoginResult(sid, sp_id, uid, appid,
				sdkVersion, appID);
		Log.d("xiaomi", "登陆成功上传参数 = " + loginResult.toJsonString());
		return loginResult;
	}

	// private String encodeLoginResult(String sid, String token) {
	//
	// JSONObject json = new JSONObject();
	// try {
	// json.put("sid", sid);
	// json.put("token", token);
	// } catch (Exception e) {
	// e.printStackTrace();
	// }
	//
	// return json.toString();
	// }

	public void pay(PayParams params) {

		if (!isLogined()) {
			U8SDK.getInstance().onResult(U8Code.CODE_INIT_FAIL,
					"The sdk is not logined.");
			return;
		}

		if (!SDKTools.isNetworkAvailable(U8SDK.getInstance().getContext())) {
			U8SDK.getInstance().onResult(U8Code.CODE_NO_NETWORK,
					"The network now is unavailable");
			return;
		}

		MiBuyInfo miBuyInfo = new MiBuyInfo();
		miBuyInfo.setCpOrderId(params.getOrderID());// 璁㈠崟鍙峰敮涓�锛堜笉涓虹┖锛�
		miBuyInfo.setCpUserInfo(""); // 姝ゅ弬鏁板湪鐢ㄦ埛鏀粯鎴愬姛鍚庝細閫忎紶缁機P鐨勬湇鍔″櫒
		miBuyInfo.setAmount(params.getPrice()); // 蹇呴』鏄ぇ浜�1鐨勬暣鏁帮紝10浠ｈ〃10绫冲竵锛屽嵆10鍏冧汉姘戝竵锛堜笉涓虹┖锛�

		// 鐢ㄦ埛淇℃伅锛岀綉娓稿繀椤昏缃�佸崟鏈烘父鎴忔垨搴旂敤鍙��
		Bundle mBundle = new Bundle();
		mBundle.putString(GameInfoField.GAME_USER_BALANCE, params.getCoinNum()
				+ ""); // 鐢ㄦ埛浣欓
		mBundle.putString(GameInfoField.GAME_USER_GAMER_VIP, params.getVip()); // vip绛夌骇
		mBundle.putString(GameInfoField.GAME_USER_LV, params.getRoleLevel()
				+ ""); // 瑙掕壊绛夌骇
		mBundle.putString(GameInfoField.GAME_USER_PARTY_NAME, "榛樿"); // 宸ヤ細锛屽府娲�
		mBundle.putString(GameInfoField.GAME_USER_ROLE_NAME,
				params.getRoleName()); // 瑙掕壊鍚嶇О
		mBundle.putString(GameInfoField.GAME_USER_ROLEID, params.getRoleId()); // 瑙掕壊id
		mBundle.putString(GameInfoField.GAME_USER_SERVER_NAME,
				params.getServerName()); // 鎵�鍦ㄦ湇鍔″櫒
		miBuyInfo.setExtraInfo(mBundle); // 璁剧疆鐢ㄦ埛淇℃伅

		MiCommplatform.getInstance().miUniPay(U8SDK.getInstance().getContext(),
				miBuyInfo, new OnPayProcessListener() {
					@Override
					public void finishPayProcess(int code) {
						switch (code) {
						case MiErrorCode.MI_XIAOMI_PAYMENT_SUCCESS:
							U8SDK.getInstance().onResult(
									U8Code.CODE_PAY_SUCCESS, "pay success");
							break;
						case MiErrorCode.MI_XIAOMI_PAYMENT_ERROR_ACTION_EXECUTED:
							// 璐拱鎴愬姛
							U8SDK.getInstance().onResult(U8Code.CODE_PAY_FAIL,
									"paying");
							break;
						case MiErrorCode.MI_XIAOMI_PAYMENT_ERROR_CANCEL:
							U8SDK.getInstance().onResult(U8Code.CODE_PAY_FAIL,
									"pay cancel");
							break;
						default:
							// 璐拱澶辫触
							U8SDK.getInstance().onResult(U8Code.CODE_PAY_FAIL,
									"pay failed. code:" + code);
							break;
						}
					}
				});
	}

	public boolean isInited() {

		return this.state.ordinal() >= SDKState.StateInited.ordinal();
	}

	public boolean isLogined() {

		return this.state.ordinal() >= SDKState.StateLogined.ordinal();
	}
}
